package org.jeecg.modules.demo.soSaleOrder.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.dto.message.TemplateMessageDTO;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.demo.caiWuSkd.entity.CwSkd;
import org.jeecg.modules.demo.caiWuSkd.service.ICwSkdService;
import org.jeecg.modules.demo.cwSaleInvoice.entity.CwSaleInvoice;
import org.jeecg.modules.demo.cwSaleInvoice.service.ICwSaleInvoiceService;
import org.jeecg.modules.demo.demo.entity.PuContract;
import org.jeecg.modules.demo.demo.service.IPuContractService;
import org.jeecg.modules.demo.pusettlement.entity.PuSettlement;
import org.jeecg.modules.demo.pusettlement.service.IPuSettlementService;
import org.jeecg.modules.demo.soFeiyong.service.ISoFeiyongService;
import org.jeecg.modules.demo.soFyft.entity.SoFyft;
import org.jeecg.modules.demo.soOrderDetail.entity.SoOrderDetail;
import org.jeecg.modules.demo.soOrderDetail.service.ISoOrderDetailService;
import org.jeecg.modules.demo.soQualityOrder.entity.SoQualityOrder;
import org.jeecg.modules.demo.soQualityOrder.service.ISoQualityOrderService;
import org.jeecg.modules.demo.soSaleOrder.entity.SoSaleOrder;
import org.jeecg.modules.demo.soSaleOrder.service.ISoSaleOrderService;
import org.jeecg.modules.demo.soSettlement.entity.SoSettlement;
import org.jeecg.modules.demo.soSettlement.entity.SoSettlementVo;
import org.jeecg.modules.demo.soSettlement.service.ISoSettlementService;
import org.jeecg.modules.demo.utils.DateUtils;
import org.jeecg.modules.demo.utils.HttpClientUtil;
import org.jeecg.modules.demo.utils.ReflectUtil;
import org.jeecg.modules.demo.utils.generateOddUtil;
import org.jeecg.modules.demo.yxqcysOrder.entity.YxQcysOrder;
import org.jeecg.modules.demo.yxqcysOrder.service.IYxQcysOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Description: 销售订单
 * @Author: jeecg-boot
 * @Date: 2021-12-06
 * @Version: V1.0
 */
@Api(tags = "销售订单")
@RestController
@RequestMapping("/sale/soSaleOrder")
@Slf4j
public class SoSaleOrderController extends JeecgController<SoSaleOrder, ISoSaleOrderService> {
    @Autowired
    private ISoSaleOrderService soSaleOrderService;

    @Autowired
    private ISoOrderDetailService soOrderDetailService;
    @Autowired
    private IPuContractService puContractService;
    @Autowired
    private ISoQualityOrderService soQualityOrderService;
    @Autowired
    private ISoSettlementService soSettlementService;
    @Autowired
    private ICwSaleInvoiceService cwSaleInvoiceService;
    @Autowired
    private ICwSkdService cwSkdService;
    @Autowired
    private IPuSettlementService puSettlementService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    @Autowired
    private ISoFeiyongService soFeiyongService;
    @Autowired
    private IYxQcysOrderService yxQcysOrderService;
    @Value(value = "${logisticsInformationUrl}")
    private String logisticsInformationUrl;

    private static final String TITLE = "单据审核";

    private String getMessage(String name,String date) {
        String str ="由【"+name+"】于【"+date+"】发起的销售发票单需要您的审核，请及时查看！";
        return str;
    }

    /**
     * 分页列表查询
     *
     * @param soSaleOrder
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "销售订单-分页列表查询")
    @ApiOperation(value = "销售订单-分页列表查询", notes = "销售订单-分页列表查询")
    @GetMapping(value = "/list")
    @PermissionData(pageComponent="yunxiao/sales/SoSaleOrderList")
    public Result<?> queryPageList(SoSaleOrder soSaleOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SoSaleOrder> queryWrapper = QueryGenerator.initQueryWrapper(soSaleOrder, req.getParameterMap());
//		queryWrapper.eq("SO_STATUS",0);
        queryWrapper.eq("IS_DELETE", 0);
            queryWrapper.isNull("QC_TYPE");
//		queryWrapper.ne("YW_TYPE",3);
        if(ReflectUtil.isObjectNull(soSaleOrder)){
            queryWrapper.ne("SO_STATUS",2);
        }
        Page<SoSaleOrder> page = new Page<SoSaleOrder>(pageNo, pageSize);
        IPage<SoSaleOrder> pageList = soSaleOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    @AutoLog(value = "期初销售订单-分页列表查询")
    @ApiOperation(value = "期初销售订单-分页列表查询", notes = "期初销售订单-分页列表查询")
    @GetMapping(value = "/qclist")
    @PermissionData(pageComponent="yunxiao/sales/QcSoSaleOrderList")
    public Result<?> queryQcList(SoSaleOrder soSaleOrder,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<SoSaleOrder> queryWrapper = QueryGenerator.initQueryWrapper(soSaleOrder, req.getParameterMap());
//		queryWrapper.eq("SO_STATUS",0);
        queryWrapper.eq("IS_DELETE", 0);
//        queryWrapper.eq("YW_TYPE",3);
        queryWrapper.isNotNull("QC_TYPE");
        if(ReflectUtil.isObjectNull(soSaleOrder)){
            queryWrapper.ne("SO_STATUS",2);
        }
        Page<SoSaleOrder> page = new Page<SoSaleOrder>(pageNo, pageSize);
        IPage<SoSaleOrder> pageList = soSaleOrderService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    //生成预开发票单
    @PostMapping(value = "/addSoInvoice")
    public Result<?> addSoInvoice(@RequestBody JSONObject jsonObject,HttpServletRequest req) {
        if (soSaleOrderService.addSoInvoice(jsonObject, req)) {
            return Result.OK("生成预开发票单成功！");
        }
        return Result.error("生成预开发票单失败！");

    }

    @PostMapping(value = "/getLogisticsInformation")
    public String getLogisticsInformation(@RequestBody SoSaleOrder soSaleOrder){
        Gson gson = new Gson();
        Map map = new HashMap();
        try{
            if(soSaleOrder.getYsType().equals("水路")){
                Map<String, Object> data = new HashMap<>();
                data.put("contractNo", soSaleOrder.getSoConNo());
                //测试数据
//                data.put("contractNo", "HT2022112301");
                String json = HttpClientUtil.doPostJson(logisticsInformationUrl,data);
                return json;
            }else{
                map.put("code",500);
                map.put("message","该订单运输方式不支持查看物流信息！");
                String json = gson.toJson(map);
                return json;
            }
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("message","系统错误！");
            String json = gson.toJson(map);
            return json;
        }
    }

    /**
     * 添加
     *
     * @param soSaleOrder
     * @return
     */
    @AutoLog(value = "销售订单-添加")
    @ApiOperation(value = "销售订单-添加", notes = "销售订单-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody SoSaleOrder soSaleOrder,HttpServletRequest req) {
        String str = soSaleOrderService.getMaxCode();
        Map<String,String> map = new HashMap<>();
        if(str==null){
            map.put("maxCode",null);
        }else{
            map.put("maxCode",str);
        }
        String tenantId = req.getHeader("tenant-id");
        String tname = soSaleOrderService.getTname(tenantId);
        String name = tname+"QCXS_";
        String resultCode = generateOddUtil.createCode(map,name);
        soSaleOrder.setSoOrder(resultCode);
        soSaleOrder.setSoStatus(0);
        soSaleOrder.setIsDelete(0);
        soSaleOrder.setSoLjck(BigDecimal.valueOf(0));
        soSaleOrder.setSoKck(soSaleOrder.getSoTotail());
        soSaleOrder.setIsQuality(0);
        if ("2".equals(soSaleOrder.getQcType())){
            soSaleOrder.setSoKck(BigDecimal.valueOf(0));
            soSaleOrder.setSoLjck(soSaleOrder.getSoTotail());
            soSaleOrder.setIsQuality(1);
        }
        soSaleOrderService.save(soSaleOrder);
        return Result.OK("添加成功！");
    }

    @PostMapping(value = "/getXsPieChatData")
    public String getXsPieChatData(@RequestParam(name="beginTime",required=false)String beginTime,@RequestParam(name="endTime",required=false)String endTime){
        Gson gson = new Gson();
        Map map = new HashMap();
        try{
            Map<String,Double> orderMap = soSaleOrderService.getXSOrderQuantity(beginTime,endTime);
            Map<String,Double>  qualityMap = soSaleOrderService.getXSQualityIQ(beginTime,endTime);
            Map<String,Double>  settlementMap = soSaleOrderService.getXSSettlementVolume(beginTime,endTime);
            Map<String,Double>  invoiceMap = soSaleOrderService.getXSInvoiceQuantity(beginTime,endTime);
            map.put("orderQuantity",orderMap.get("ORDERQUANTITY"));
            map.put("qualityIQ",qualityMap.get("QUALITYIQ"));
            map.put("settlementVolume",settlementMap.get("SETTLEMENTVOLUME"));
            map.put("invoiceQuantity",invoiceMap.get("INVOICEQUANTITY"));
            map.put("code",200);
            map.put("message","成功！");
            String json = gson.toJson(map);
            return json;
        }catch (Exception e){
            e.printStackTrace();
            map.put("code",500);
            map.put("message","系统错误！");
            String json = gson.toJson(map);
            return json;
        }
    }


    /**
     * 编辑
     *
     * @param soSaleOrder
     * @return
     */
    @AutoLog(value = "销售订单-编辑")
    @ApiOperation(value = "销售订单-编辑", notes = "销售订单-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody SoSaleOrder soSaleOrder) {
        try {

            LoginUser user = sysBaseAPI.getUserById(soSaleOrder.getSoStaff());
            TemplateMessageDTO templateMessageDTO = new TemplateMessageDTO();
            templateMessageDTO.setFromUser("管理员");
            templateMessageDTO.setToUser(soSaleOrder.getShName()+",");
            templateMessageDTO.setTitle(TITLE);
            templateMessageDTO.setTemplateCode("order");
            Map<String, String> templateParam = new HashMap<>();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String date= simpleDateFormat.format(new Date());
            templateParam.put("ts_date",date);
            templateParam.put("ts_content", getMessage(user != null?user.getRealname():"该业务员不存在！", date));
            templateParam.put("checkOrder",soSaleOrder.getSoOrder());
            templateParam.put("cd_url","/sales/SoSaleOrderList/list");
            templateMessageDTO.setTemplateParam(templateParam);
            sysBaseAPI.sendTemplateAnnouncement(templateMessageDTO);


            if (soSaleOrder.getSoKck() == null) {
                soSaleOrder.setSoKck(soSaleOrder.getSoTotail());
            }
            soSaleOrderService.updateById(soSaleOrder);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("操作失败");
        }

        return Result.OK("编辑成功!");
    }

    //审核弃审
    @PutMapping(value = "/editShenhe")
    public Result<?> editShenhe(@RequestBody SoSaleOrder soSaleOrder) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (soSaleOrder.getShName().equals(sysUser.getId())) {
            if (soSaleOrder.getSoStatus() == 0) { //弃审
                soSaleOrder.setShTime(null);
                List<YxQcysOrder> so = yxQcysOrderService.getlistBysoNo(soSaleOrder.getSoOrder());
                if (so.size() > 0) {
                    return Result.error(300, "此订单已生成期初应收款单，不能弃审！");
                }
            } else if (soSaleOrder.getSoStatus() == 1) {  //审核
                soSaleOrder.setShTime(new Date());
                if (soSaleOrder.getSoKck() == null) {
                    soSaleOrder.setSoKck(soSaleOrder.getSoTotail());
                }
            }

        } else {
            return Result.error(300, "您不是当前单据的指定审核人！");
        }

        soSaleOrderService.updateById(soSaleOrder);
        return Result.OK("编辑成功!");
    }

    @PutMapping(value = "/kaiqi")
    public Result<?> kaiqi(@RequestBody SoSaleOrder soSaleOrder) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (soSaleOrder.getShName().equals(sysUser.getId())) {
            soSaleOrderService.updateById(soSaleOrder);
        } else {
            return Result.error(300, "您无此权限！");
        }
        return Result.OK("开启成功!");
    }

    //删除订单并修改合同状态
    @PutMapping(value = "/editAndHtzt")
    public Result<?> editAndHtzt(@RequestBody SoSaleOrder soSaleOrder) {
        String soConNo = soSaleOrder.getSoConNo();
        soSaleOrderService.removeById(soSaleOrder.getId());
        if (soConNo != null&& !soConNo.isEmpty()){
            PuContract puContract = puContractService.getBysoConNo(soConNo);
            puContract.setStatus("0");
            puContractService.updateById(puContract);
        }

        return Result.OK("编辑成功!");
    }

    //销售订单进度条
    @GetMapping(value = "/queryBySoNo")
    public Result<?> queryBySoNo(@RequestParam(name = "id", required = true) String id) {
        Map<String, Object> map = new HashMap<>();
        SoSaleOrder sso = soSaleOrderService.getBysoNo(id);
        List<SoOrderDetail> sod = soOrderDetailService.getBysoNo(id);
        List<SoQualityOrder> soq = soQualityOrderService.getBysoNo(id);
        List<SoSettlement> sst = soSettlementService.getBysoNo(id);
        List<CwSaleInvoice> csi = cwSaleInvoiceService.getBysoNo(id);
        List<CwSaleInvoice> ykp = cwSaleInvoiceService.getYkpBysoNo(id);
        List<CwSkd> csk = cwSkdService.getBysoNo(id);
        List<CwSkd> ysk = cwSkdService.getYskBysoNo(id);
        List<SoFyft> fy = soFeiyongService.getFyxxBysoNo(id);
        map.put("xs", sso);
        map.put("ck", sod);
        map.put("zj", soq);
        map.put("js", sst);
        map.put("fp", csi);
        map.put("ykfp", ykp);
        map.put("sk", csk);
        map.put("ysk", ysk);
        map.put("fy", fy);
        return Result.OK(map);
    }

    //根据租户的开始时间获取上一年份
    @GetMapping(value = "/queryzhdate")
    public Result<?> queryzhdate(HttpServletRequest req) {
        String tenantId = req.getHeader("tenant-id");
        Date tdate = soSaleOrderService.getTdate(tenantId);
        Date date = DateUtils.getUpYear(tdate);
//        Calendar ca = Calendar.getInstance();//得到一个Calendar的实例
//        ca.setTime(tdate);   //设置时间为当前时间
//        ca.add(Calendar.YEAR, -1); //年份-1
        return Result.OK(date);
    }

    //首页销售额
    @GetMapping(value = "/queryXseBymonth")
    public Result<?> queryXseBymonth() {
        List<SoSettlementVo> cw = cwSaleInvoiceService.queryXseBymonth();
        return Result.OK(cw);
    }

    //首页销售趋势
    @GetMapping(value = "/queryXsqsBymonth")
    public Result<?> queryXsqsBymonth() {
        List<SoSettlementVo> sos = soSettlementService.queryXsqsBymonth();
        return Result.OK(sos);
    }

    //首页收入分析
    @GetMapping(value = "/querySrfx")
    public Result<?> querySrfx(@RequestParam(name = "beginTime", required = true)String beginTime,
                               @RequestParam(name = "endTime", required = true)String endTime) {
        List<SoSettlementVo> sos = soSettlementService.querySrfx(beginTime,endTime);
        return Result.OK(sos);
    }

    //首页采购趋势
    @GetMapping(value = "/queryCaigouqushi")
    public Result<?> queryCaigouqushi() {
        List<PuSettlement> sos = puSettlementService.queryCaigouqushi();
        return Result.OK(sos);
    }

    //首页应收
    @GetMapping(value = "/queryYingshou")
    public Result<?> queryYingshou() {
        Map<String,Object> map = new HashMap<>();
        List<SoSettlementVo> sos = soSaleOrderService.queryYingshou();
        SoSettlementVo ss = soSaleOrderService.queryYingshou1();
        map.put("5",sos);
        map.put("1",ss);
        return Result.OK(map);
    }

    //首页应付
    @GetMapping(value = "/queryYingfu")
    public Result<?> queryYingfu() {
        Map<String,Object> map = new HashMap<>();
        List<SoSettlementVo> sos = soSaleOrderService.queryYingfu();
        SoSettlementVo ss = soSaleOrderService.queryYingfu1();
        map.put("5",sos);
        map.put("1",ss);
        return Result.OK(map);
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售订单-通过id删除")
    @ApiOperation(value = "销售订单-通过id删除", notes = "销售订单-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        try {
            SoSaleOrder soSaleOrder = soSaleOrderService.getById(id);
            if (soSaleOrder.getSoStatus() == 1) {
                return Result.error("订单已审核，无法删除！");
            }
            soSaleOrder.setIsDelete(1);
            soSaleOrderService.updateById(soSaleOrder);
            return Result.OK("删除成功!");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error(500, "系统错误！");
        }
//		soSaleOrderService.removeById(id);
//		return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "销售订单-批量删除")
    @ApiOperation(value = "销售订单-批量删除", notes = "销售订单-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.soSaleOrderService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "销售订单-通过id查询")
    @ApiOperation(value = "销售订单-通过id查询", notes = "销售订单-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        SoSaleOrder soSaleOrder = soSaleOrderService.getById(id);
        if (soSaleOrder == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(soSaleOrder);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param soSaleOrder
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, SoSaleOrder soSaleOrder) {
        return super.exportXls(request, soSaleOrder, SoSaleOrder.class, "销售订单表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, SoSaleOrder.class);
    }

}
